package com.intelligent.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.intelligent.mapper.ReceiptOrderMapper;
import com.intelligent.mapper.CustomerManagementMapper;
import com.intelligent.mapper.CustomerInfoMapper;
import com.intelligent.mapper.TUserMapper;
import com.intelligent.pojo.ReceiptOrder;
import com.intelligent.pojo.CustomerManagement;
import com.intelligent.pojo.CustomerInfo;
import com.intelligent.pojo.TUser;
import com.intelligent.service.ReceiptOrderService;
import com.intelligent.vo.ReceiptOrderPageReq;
import com.intelligent.vo.ReceiptOrderResp;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.stream.Collectors;

@Service
public class ReceiptOrderServiceImpl extends ServiceImpl<ReceiptOrderMapper, ReceiptOrder>
    implements ReceiptOrderService{

    @Resource
    private CustomerManagementMapper customerManagementMapper;

    @Resource
    private CustomerInfoMapper customerInfoMapper;

    @Resource
    private TUserMapper tUserMapper;

    @Override
    public Page<ReceiptOrderResp> page(ReceiptOrderPageReq req) {
        Page<ReceiptOrder> entityPage = new Page<>(req.getPageNum(), req.getPageSize());
        LambdaQueryWrapper<ReceiptOrder> qw = new LambdaQueryWrapper<>();
        
        if (req.getReceiptOrderNo() != null && !req.getReceiptOrderNo().trim().isEmpty()) {
            qw.like(ReceiptOrder::getReceiptOrderNo, req.getReceiptOrderNo().trim());
        }
        if (req.getCustomerId() != null) {
            qw.eq(ReceiptOrder::getCustomerId, req.getCustomerId());
        }
        if (req.getRelatedSalesOrder() != null && !req.getRelatedSalesOrder().trim().isEmpty()) {
            qw.like(ReceiptOrder::getRelatedSalesOrder, req.getRelatedSalesOrder().trim());
        }
        if (req.getReceiptStatus() != null) {
            qw.eq(ReceiptOrder::getReceiptStatus, req.getReceiptStatus());
        }
        if (req.getUId() != null) {
            qw.eq(ReceiptOrder::getUId, req.getUId());
        }
        
        qw.orderByDesc(ReceiptOrder::getId);
        this.page(entityPage, qw);

        Page<ReceiptOrderResp> voPage = new Page<>(entityPage.getCurrent(), entityPage.getSize(), entityPage.getTotal());
        voPage.setRecords(entityPage.getRecords().stream().map(this::toResp).collect(Collectors.toList()));
        return voPage;
    }

    @Override
    public ReceiptOrderResp detail(Integer id) {
        ReceiptOrder receiptOrder = this.getById(id);
        return receiptOrder == null ? null : toResp(receiptOrder);
    }

    @Override
    public boolean create(ReceiptOrder receiptOrder) {
        // 自动生成收款单号（前缀 SK + 日期 + 流水）
        if (receiptOrder.getReceiptOrderNo() == null || receiptOrder.getReceiptOrderNo().trim().isEmpty()) {
            String ts = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
            receiptOrder.setReceiptOrderNo("SK" + ts);
        }
        // 自动计算待核销金额
        if (receiptOrder.getReceivableAmount() != null && receiptOrder.getWrittenOffAmount() != null) {
            receiptOrder.setToBeWrittenOff(receiptOrder.getReceivableAmount().subtract(receiptOrder.getWrittenOffAmount()));
        }
        return this.save(receiptOrder);
    }

    private ReceiptOrderResp toResp(ReceiptOrder receiptOrder) {
        ReceiptOrderResp resp = new ReceiptOrderResp();
        resp.setId(receiptOrder.getId());
        resp.setReceiptOrderNo(receiptOrder.getReceiptOrderNo());
        resp.setReceiptStatus(receiptOrder.getReceiptStatus());
        resp.setCustomerId(receiptOrder.getCustomerId());
        resp.setRelatedSalesOrder(receiptOrder.getRelatedSalesOrder());
        resp.setReceivableAmount(receiptOrder.getReceivableAmount());
        resp.setWrittenOffAmount(receiptOrder.getWrittenOffAmount());
        resp.setToBeWrittenOff(receiptOrder.getToBeWrittenOff());
        resp.setUId(receiptOrder.getUId());
        resp.setCreationDate(receiptOrder.getCreationDate());

        // 获取客户名称
        if (receiptOrder.getCustomerId() != null) {
            // 兼容两种外键：
            // 1) receipt_order.customer_id 指向 customer_management.id
            CustomerManagement cm = customerManagementMapper.selectById(receiptOrder.getCustomerId());
            if (cm != null) {
                resp.setCustomerName(cm.getCustomerName());
            } else {
                // 2) receipt_order.customer_id 指向 customer_info.id，再由 customer_info.customerId -> customer_management.id
                CustomerInfo ci = customerInfoMapper.selectById(receiptOrder.getCustomerId());
                if (ci != null && ci.getCustomerId() != null) {
                    CustomerManagement cm2 = customerManagementMapper.selectById(ci.getCustomerId());
                    if (cm2 != null) {
                        resp.setCustomerName(cm2.getCustomerName());
                    }
                }
            }
        }

        // 获取财务人员姓名
        if (receiptOrder.getUId() != null) {
            TUser user = tUserMapper.selectById(receiptOrder.getUId());
            if (user != null) {
                resp.setFinanceUserName(user.getRealName() != null ? user.getRealName() : user.getUsername());
            }
        }

        return resp;
    }
}




